<!--
 * @Author: tenet 18742176629@163.com
 * @Date: 2024/7/30 下午6:12
 * @LastEditors: tenet 18742176629@163.com
 * @LastEditTime: 2024/7/30 下午6:12
 * @FilePath: G:/token-for-token-front-admin/src/views/userWallet\index.vue
 * @Description: 用户钱包配置
-->
<template>
  <Header>
    <template #title>{{ t('title.UserWallet') }}</template>
  </Header>
  <div class="generate">
    <el-button type="primary" @click="handleClick('add')">{{ t('userWallet.ConfigAdd') }}</el-button>
  </div>

  <!--  用户钱包配置 dialog -->
  <el-dialog v-model="isDialog" :title="dialogText" width="500" center @close="resetForm">
    <el-form :model="form" :rules="rules" ref="ruleRef" label-width="auto" style="max-width: 600px" label-position="top">
      <el-form-item prop="chainConfigId" :label="t('table.ChainName')">
        <el-select v-model.trim="form.chainConfigId" :loading="loading"
                   :placeholder="t('userWallet.SelectChainName')">
          <el-option v-for="(item, key) in chainList" :key="key" :label="item.chainName" :value="item.id"/>
        </el-select>
      </el-form-item>
      <!-- <el-form-item prop="feeAddress" :label="t('userWallet.FeeAddress')">
        <el-input v-model.trim="form.feeAddress" type="text" :placeholder="t('userWallet.FeeAddress')"/>
      </el-form-item> -->
      <el-form-item prop="collectAddress" :label="t('userWallet.CollectAddress')">
        <el-input v-model.trim="form.collectAddress" type="text" :placeholder="t('userWallet.CollectAddress')"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit" :loading="loading">{{ t('global.Submit') }}</el-button>
      </div>
    </template>
  </el-dialog>


  <div class="table">
    <el-table :data="tableData" border style="width: auto; height: 700px" v-loading="loading">
      <el-table-column prop="chainConfigName" :label="t('table.ChainName')" width="200" align="center"/>
      <el-table-column prop="feeAddress" :label="t('table.FeeAddress')" width="auto" align="center"/>
      <el-table-column prop="collectAddress" :label="t('table.CollectAddress')" width="auto" align="center"/>

      <el-table-column fixed="right" :label="t('global.Operation')" width="150" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleClick('update',scope)">{{ t('global.Update') }}</el-button>
<!--           <el-button link type="danger" size="small" @click="handleClick('delete',scope)">{{ t('global.Delete') }}</el-button>-->
          <el-popconfirm :title="t('message.DeleteTips')" @confirm="confirmSubmit(scope)">
            <template #reference>
              <el-button link type="danger" size="small">{{ t('global.Delete') }}</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <div class="page">
    <el-pagination v-model:current-page="pageIndex" :page-size="pageSize" layout="total, prev, pager, next"
                   :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange"/>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref, unref} from 'vue'
import {ElMessage, ElPagination, ElTable} from 'element-plus'
import Header from "../layout/header.vue";
import {creatUserConfig, updateChain, getUserConfigList, chainConfigs, chainTokens, updateUserConfig, deleteUserConfig } from '@/require/api.js'
import {useI18n} from "vue-i18n";
import {formatTimestamp} from "@/utils/timeStamp.js";

const {t} = useI18n();

// 在组件被挂载后执行
onMounted(() => {
  getChainConfigs() // 获取配置列表
  getList();
});


const pageSize = ref(10)
const pageIndex = ref(1)
const total = ref(0)
const chainList = ref([]) // 配置列表
const tableData = ref([])
const loading = ref(false)
const btnType = ref(); // 按钮类型
const dialogText = ref(t('userWallet.ConfigAdd')) // dialog标题
const isDialog = ref(false) // 控制 dialog


const ruleRef = ref(null)


// form
const form = reactive({
  mainCoinType: undefined, // 初始化为一个空对象
  withdrawAddress: '',   //提现地址
  chainName: '',

  id:'', // 修改时的id
  chainConfigId: "", // 链配置ID
  // feeAddress: "", // 手续费地址
  collectAddress: "", // 归集地址
})


// 点击按钮事件
async function handleClick(type, scope) {
  try {
    btnType.value = type;
    isDialog.value = true;
    if(btnType.value === 'add'){
      //  新增按钮
      dialogText.value = t('userWallet.ConfigAdd')
    }else if(btnType.value === 'update'){
      //  修改按钮
      dialogText.value = t('userWallet.ConfigEdit')
      form.chainConfigId = scope.row.chainConfigId
      // form.feeAddress = scope.row.feeAddress
      form.collectAddress = scope.row.collectAddress
      form.id = scope.row.id
    }
  }catch (e) {
    console.log(e)
  }
}


// 提交表单
async function onSubmit(){
  try {
    loading.value = true
    if(btnType.value === 'add'){
      const { code, data, msg } = await creatUserConfig({
        collectAddress: form.collectAddress,
        // feeAddress: form.feeAddress,
        chainConfigId: form.chainConfigId,
      })
      if(code === 200){
        ElMessage.success(t('message.AddSuccess'))
      }else{
        ElMessage.error(msg)
      }
    }else if( btnType.value === 'update'){
      const { code, data, msg } = await updateUserConfig(form.id,{
        collectAddress: form.collectAddress,
        // feeAddress: form.feeAddress,
        chainConfigId: form.chainConfigId,
      })
      if(code === 200){
        ElMessage.success(t('message.EditSuccess'))
      }else{
        ElMessage.error(msg)
      }
    }
  }catch (e) {
    console.log(e)
  } finally {
    await getList()
    loading.value = false
    isDialog.value = false
  }
}



// 删除数据方法
async function confirmSubmit(scope){
  try {
    const { code, data, msg } = await deleteUserConfig( scope.row.id )
        if(code === 200){
          ElMessage.success(t('message.DeleteSuccess'))
        }else{
          ElMessage.error(msg)
        }
  } catch (e) {
    console.log(e)
  } finally {
    await getList()
  }
}


// 表单验证规则
const rules = reactive({
  chainConfigId: [
    {required: true, message: t('message.ChainNameNotNull'), trigger: 'blur'},
  ],
  // feeAddress: [
  //   {required: true, message: t('message.FeeAddress'), trigger: 'blur'},
  // ],
  collectAddress: [
    {required: true, message: t('message.CollectAddress'), trigger: 'blur'},
  ],
})


// 获取用户配置列表
async function getList() {
  try {
    loading.value = true
    const {code, data, msg} = await getUserConfigList({})
    if (code === 200) {
      tableData.value = data.list
      total.value = data.total
    } else {
      ElMessage.error(msg)
    }
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}


// 获取配置列表方法
async function getChainConfigs(){
  const { code, data, msg } = await chainConfigs()
  if (code === 200) {
    chainList.value = data
  } else {
    ElMessage.error(msg)
  }
}

// 重置表单
function resetForm() {
  // form.feeAddress = undefined
  form.collectAddress = undefined
  form.chainConfigId = undefined
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

// 分页
const handleCurrentChange = (val) => {
  pageIndex.value = val
  getList()
}

</script>

<style scoped lang="less">
.generate {
  text-align: left;
  margin: 10px
}
.myTable{
  .title{
    margin:.2rem 0 ;
  }
}

.fee{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
}
.coll{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  margin: .5rem 0;
}

.withdraw{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
}
</style>